package cn.hxzy.user.service.impl;

import cn.hxzy.common.domain.School;
import cn.hxzy.common.domain.User;
import cn.hxzy.common.domain.UserClass;
import cn.hxzy.common.domain.UserInfo;
import cn.hxzy.user.mapper.UserMapper;
import cn.hxzy.user.service.UserService;
import cn.hxzy.common.util.JwtUtils;
import cn.hxzy.common.util.MsmUtil;
import cn.hxzy.common.util.ThreadLocalUtil;
import com.aliyun.oss.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 项目名: education-platform
 * 当前用户: 18735
 * 创建日期: 2024/6/22 下午2:46
 * 项目介绍:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final Integer CODE_LENGTH = 6;

    /**
     * 登录
     * @param userName 账号
     * @param userPass 密碼
     * @return jwt
     */
    @Override
    public String login(String userName, String userPass) {

        User user = userMapper.login(userName, userPass);
        if (ObjectUtils.isEmpty(user)){
            throw  new RuntimeException("账号或密码错误");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString;
        try {
            jsonString = objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        String token = JwtUtils.createJWT(jsonString);
        return token;
    }

    /**
     * 修改用户信息
     * @param user 用戶信息
     * @return 1 修改成功
     */
    @Override
    public Boolean updateUser(User user) {
        int update = userMapper.update(user, new UpdateWrapper<User>().eq("user_id", ThreadLocalUtil.getUser().getUserId()));
        if (update!=1){
            return false;
        }else {
            return true;
        }

    }




    /**
     * 根据id查询用户信息
     * @return 用户信息
     */
    @Override
    public User selectById() {
        return userMapper.selectById(2L);
    }

    @Override
    public int updatePwd(Map map) {
        //获取当前登录对象
        User user = ThreadLocalUtil.getUser();
        //根据redis里面的账号在数据库获取用户对象
        User u1 = userMapper.selectById(user.getUserId());
        String oldPwd = (String) map.get("old_pwd");
        String newPwd = (String) map.get("new_pwd");
        String rePwd = (String) map.get("re_pwd");
        //进行比对
        if (!u1.getUserPass().equals(oldPwd)){
            return -1;//密码错误
        }
        //两次密码比对
        if (!newPwd.equals(rePwd)){
            return -2;//两次密码不一致
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",user.getUserId());
        updateWrapper.set("user_pass",map.get("new_pwd").toString());
        int update = userMapper.update(null,updateWrapper);
        return update;

    }
    @Override
    public User selectUserInfo() {
        //获取当前用户id
        Long userId = ThreadLocalUtil.getUser().getUserId();
        User user1 = userMapper.GetUserinfo(userId);
        return user1;
    }


    /**
     * 新增学校
     * @param school
     * @return 1 新增成功
     */
    @Override
    public int save(School school) {
        return 0;
    }

    /**
     * 获取验证码
     * @param userPhone 手机号
     * @return 验证码
     */
    @Override
    public String getCode(String userPhone) {
        String code = "";
        //首先从redis中获取
        code = redisTemplate.opsForValue().get(userPhone);
        if (!StringUtils.isNullOrEmpty(code)){
            return code;
        }
        Random random = new Random();
        //生成验证码,传递阿里云进行发送
        for (int i = 0; i < CODE_LENGTH; i++) {
            code += random.nextInt(10);
        }
        Map<String,String> param = new HashMap<>();
        param.put("code",code);
        if (MsmUtil.send(param,userPhone)){
            redisTemplate.opsForValue().set(userPhone,code,60);
            return code;
        }
        log.error("Failed to send SMS code to phone number: " + userPhone); // 记录发送失败日
        return null;
    }

    /**
     * 手机号登录
     * @param userPhone 手机号
     * @param code 验证码
     * @return jwt
     */
    @Override
    public String loginByCode(String userPhone, String code) {

        if (code.equals(redisTemplate.opsForValue().get(userPhone))){

            Long userId = userMapper.loginByCode(userPhone);

            if (userId==0){
                return null;
            }

            //根据用户编号获取用户信息存入线程
            String token = JwtUtils.createJWT(userId.toString());
            if (StringUtils.isNullOrEmpty(token)){
                return null;
            }
            User user = userMapper.selectById(userId);
            ThreadLocalUtil.setUser(user);
            redisTemplate.opsForValue().set(userId.toString(),token,60*60*2);
            return token;

        }
        return null;
    }

    /**
     * 根据编号查询班级信息
     * @return 返回用户所对应的所有班级信息
     */
    @Override
    public List<UserClass> selectClassById() {
        User user = ThreadLocalUtil.getUser();
        List<UserClass> userClassList = userMapper.selectClassById(user.getUserId());
        if (ObjectUtils.isEmpty(userClassList)){
            return null;
        }
        return userClassList;
    }



    @Override
    public Integer AddUserXX(User user) {
        Integer i = userMapper.AddUserXX(user);
        return i;
    }
    @Override
    public Integer addUserInfo(UserInfo userInfo) {
        Integer i = userMapper.addUserInfo(userInfo);
        return i;
    }

    @Override
    public Integer addUserClass(Integer userId, Integer classId) {
        Integer i = userMapper.addUserClass(userId, classId);
        return  i;
    }

    @Override
    public List<User> selectUserByClassId(Integer classId) {
        List<User> users = userMapper.selectUserByClassId(classId);
        return users;
    }

    @Override
    public Integer deleteUser(Integer userId) {
        Integer i = userMapper.deleteUser(userId);
        Integer i2 = userMapper.deleteUserTable(userId);
        return i;
    }

    // 根据id查询老师信息(别删除这个学生上传作业使用了)
    @Override
    public User selectteacherById(Integer userId) {
        return userMapper.selectById02(userId);
    }

}
